package ar.com.ford.it.fullEconomics.security;

import java.io.InputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import ar.com.ford.it.webengine.security.SessionController;
import ar.com.ford.it.webengine.wslx.WslxUser;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.itss.wsl.WSLCookie;
import com.ford.itss.wsl.WSLCookieValidator;
import com.ford.itss.wsl.WSLException;
import com.ford.itss.wsl.WSLPublicKey;
import com.ford.itss.wsl.WSLValidatorFactory;

public class FullEconomicsSessionControllerWslx extends SessionController {
	private static final String CLASS_NAME = FullEconomicsSessionControllerWslx.class
			.getName();

	private static final ILogger log = LogFactory.getInstance().getLogger(
			CLASS_NAME);

	private static InputStream internalKey;

	// FordExample
	public boolean isValidFirstRequestFordExample(HttpServletRequest request) {
		WSLCookie wslCookie = getWSLCookie(request);
		if (wslCookie != null && wslCookie.isValid())
			return true;

		return false;
	}

	public boolean isValidFirstRequest(HttpServletRequest request) {
		String METHOD_NAME = "isValidFirstRequest";
		log.entering(CLASS_NAME, METHOD_NAME);

		HttpSession session = request.getSession();

		WSLCookie wslCookie = getWSLCookie(request);
		if (wslCookie == null) {
			return false;
		}

		String cds = (String) wslCookie.getAttributes().get("userid");

		session.setAttribute("p_usr_cds", cds);
		log.exiting(CLASS_NAME, METHOD_NAME, Boolean.toString(true));
		return true;
	}

	// FordExample
	public String getUserIdFordExample(HttpServletRequest request) {
		WSLCookie wslCookie = getWSLCookie(request);

		if (wslCookie != null && wslCookie.isValid()) {
			return (String) wslCookie.getAttributes().get("userid");
		}

		return null;
	}

	public String getUserId(HttpServletRequest request) {
		WSLCookie wslCookie = getWSLCookie(request);

		if (wslCookie != null) {
			return (String) wslCookie.getAttributes().get("userid");
		}

		return null;
	}

	public void completeWslxLoad(WslxUser wslxUser, HttpServletRequest request) {
	}

	public boolean isLoggedUser(WslxUser wslxUser, HttpServletRequest request) {
		String METHOD_NAME = "isUserLogged";

		boolean result = false;
		WSLCookie wslCookie = getWSLCookie(request);

		String userCds = (String) wslCookie.getAttributes().get("userid");
		log.entering(CLASS_NAME, METHOD_NAME, userCds);
		log.info(CLASS_NAME+" Usuario: "+userCds);

		if (userCds.equalsIgnoreCase((String) wslCookie.getAttributes().get(
				"userid")))
			result = true;

		log.exiting(CLASS_NAME, METHOD_NAME, Boolean.toString(result));
		return result;
	}

	// FordExample
	public boolean isLoggedUserFordExample(WslxUser wslxUser,
			HttpServletRequest request) {
		WSLCookie wslCookie = getWSLCookie(request);
		if (wslCookie != null && wslCookie.isValid()) {
			// Cookie properties
			if (wslCookie.getAttributes().get("userid")
					.equals(wslxUser.getId()))
				return true;
		}
		return false;
	}

	/**
	 * Definir politica de acceso a la aplicacion
	 */
	public boolean validateAccessToApp(WslxUser wslxUser,
			HttpServletRequest request) {

		String METHOD_NAME = "validateAccessToApp";
		log.entering(CLASS_NAME, METHOD_NAME);

		if (wslxUser != null && wslxUser.getProfiles() != null
				&& !wslxUser.getProfiles().isEmpty()) {
			log.exiting(CLASS_NAME, METHOD_NAME, "true");
			return true;
		}

		log.exiting(CLASS_NAME, METHOD_NAME, "false");
		return false;
	}

	private WSLCookie getWSLCookie(HttpServletRequest request) {
		String METHOD_NAME = "getWSLCookie";

		WSLCookieValidator cookieValidator = null;

		try {
			WSLPublicKey[] wslkeys = { new WSLPublicKey(getWslKey()) };
			cookieValidator = WSLValidatorFactory.createWSLCookieValidator(
					WSLCookieValidator.WSL_COOKIE_V4, wslkeys);
		} catch (WSLException excep) {
			log.logp(Level.INFO, CLASS_NAME, METHOD_NAME, "error, salida 1");
			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME, "Oops", excep);
			return null;
		}

		Cookie[] cookies = request.getCookies();
		Cookie searched = getSearchedCookie(cookies);

		if (searched == null) {
			log.logp(Level.INFO, CLASS_NAME, METHOD_NAME,
					"searched es nulo, salida 2");
			return null;
		}
		return cookieValidator.validateCookie(searched.getValue(), request
				.getRemoteAddr());
	}

	private InputStream getWslKey() {

		// Agregar logica para definir key internos / externos
		if (internalKey == null)
			return this.getClass().getResourceAsStream(
					"/resources/wsl-internal.pem");
		else
			return internalKey;
	}

	private Cookie getSearchedCookie(Cookie[] cookies) {
		if (cookies == null || cookies.length == 0)
			return null;

		for (int i = 0; i < cookies.length; i++) {
			if ("WSL-credential".equals(cookies[i].getName()))
				return cookies[i];
		}
		return null;
	}

}
